<?php
use Swoole\Runtime;
use Swoole\Coroutine;
use Swoole\Coroutine\MySQL;
use function Swoole\Coroutine\run;
Runtime::enableCoroutine(true, SWOOLE_HOOK_ALL | SWOOLE_HOOK_CURL);

$start_time = microtime(true);

require  __DIR__ .'/../global_default_function.php';

function getCreativeFeed($header) {
	$doResponse = HttpPost('https://api.baidu.com/json/feed/v1/CreativeFeedService/getCreativeFeed', $header);
	if( !$doResponse ) {
		return false;
	}
	$bodyArray = json_decode($doResponse, true);
	if( !is_array($bodyArray) ) {
		return false;
	}
	if( !isset($bodyArray['header']) ) {
		return false;
	}
	if( !isset($bodyArray['header']['desc']) ) {
		return false;
	}
	if( !isset($bodyArray['body']['data'])) {
		return false;
	}
	return $bodyArray['body']['data'];
}

function getCreativeData($database, $user, $adgroup) {
	$adgroupIds = [];
	if(is_array($adgroup)){
		foreach( $adgroup as $value) {
			array_push($adgroupIds, $value['adgroupId']);
		}
	}
	$creativeFeedId = [];
	$array_chunk = array_chunk($adgroupIds, 100);
	foreach ($array_chunk as $ids) {
    $result = getCreativeFeed(json_encode([
			'header'=>[ 'username'=> $user['username'], 'password'=> $user['password'], 'token'=> $user['token'] ],
			'body'=> [
				"creativeFeedFields"=> [
						"creativeFeedId",
						"adgroupFeedId",
						"creativeFeedName",
						"status",
				],
				"idType"=> 2,// 单元ID
				"ids"=> $ids
			]
		]));
		if(is_array($result)) {
			foreach($result as $value) {
				array_push($creativeFeedId, $value['creativeFeedId']);
				$_array = getArray($adgroup, $value['adgroupFeedId'], 'adgroupId');
				if($_array) {
					$value['creativeFeedName'] = str_replace(',', '', $value['creativeFeedName']);
					$res = $database->query("select id from cfg_creative where `companyId` = '{$user['companyId']}' AND `userType` = 2 AND `userId` = '{$user['userid']}' AND `creativeId` = '{$value['creativeFeedId']}' LIMIT 1");
					if( isset($res[0]['id']) ) {
						$database->query( "UPDATE cfg_creative SET `bazaarId` = '{$user['bazaarId']}', `adgroupName` = '{$_array['adgroupName']}', `campaignName` = '{$_array['campaignName']}', `status` = '{$value['status']}', `title` = '{$value['creativeFeedName']}', `datatime` = now() WHERE id = '{$res[0]['id']}'; ");
					} else {
						$database->query("INSERT INTO cfg_creative ( `companyId`, `userType`, `userId`, `bazaarId`, `adgroupName`, `campaignId`, `campaignName`, `creativeId`, `adgroupId`, `title`, `status`, `datatime`) values (
						'{$user['companyId']}', 2, '{$user['userid']}', '{$user['bazaarId']}', '{$_array['adgroupName']}', '{$_array['campaignId']}', '{$_array['campaignName']}', '{$value['creativeFeedId']}',
              '{$value['adgroupFeedId']}', '{$value['creativeFeedName']}', '{$value['status']}', now()) " );
					}
				}
		  }
		}
	}
	switch (count($creativeFeedId)) {
		case 0:
			$database->query(" DELETE FROM cfg_creative WHERE `companyId` = {$user['companyId']} AND `userType` = 2 AND `userId` = {$user['userid']} " );
			$database->query(" DELETE FROM cfg_search WHERE `companyId` = {$user['companyId']} AND `userType` = 2 AND `userid` = {$user['userid']} AND `creativeid` > 0 " );
			break;
		case 1:
			$database->query(" DELETE FROM cfg_creative WHERE `companyId` = {$user['companyId']} AND `userType` = 2 AND `userId` = {$user['userid']} AND `creativeId` <> {$creativeFeedId[0]}" );
			$database->query(" DELETE FROM cfg_search WHERE `companyId` = {$user['companyId']} AND `userType` = 2 AND `userid` = {$user['userid']} AND `creativeid` > 0 AND `creativeid` <> {$creativeFeedId[0]} " );
			break;
		default:
			$notinId = implode(',', $creativeFeedId);
			$database->query(" DELETE FROM cfg_creative WHERE `companyId` = {$user['companyId']} AND `userType` = 2 AND `userId` = {$user['userid']} AND `creativeId` NOT IN ($notinId) " );
			$database->query(" DELETE FROM cfg_search WHERE `companyId` = {$user['companyId']} AND `userType` = 2 AND `userid` = {$user['userid']} AND `creativeid` > 0 AND `creativeid` NOT IN ($notinId) " );
	}
}

run(function() use ($argv) {
	showMessage('读取信息流创意.' );
	$config = getConfig();
	$database = new MySQL();
	$connect = $database->connect($config);
	if( $connect === false) {
		return;
	}
  $userList = $database->query('SELECT `id`, `companyId`, `rebate`, `bazaarId`, `userid`, `username`, `password`, `token` FROM cfg_expand where status = 1 and userType = 2');
	if ($userList === false) {
		showMessage($database->errno . ' - ' . $database->error);
		return;
	}
	$userArray = array_chunk($userList, $config['curlnumber']);
  foreach ($userArray as $arrayList) {
		foreach ($arrayList as $user) {
			go(function() use ($config, $user)  {
				$database = new MySQL;
				$connect = $database->connect($config);
				if( $connect === false) {
					return;
				}
				showMessage($user['username'].'读取信息流创意.' );
				$queryAdgroup = $database->query("select id, bazaarId, adgroupId, adgroupName, campaignId, campaignName from cfg_adgroup WHERE `companyId` = '{$user['companyId']}' AND `userType` = 2 AND userId = '{$user['userid']}' ");
				if( count($queryAdgroup) > 0) {
					getCreativeData($database, $user, $queryAdgroup);
				}
			});
		}
		Swoole\Coroutine::sleep(2);
	}
});

showMessage('执行耗时 ' . round((microtime(true) - $start_time), 3) . ' s');